package com.lin.netty.chat.server;

import com.lin.netty.chat.handler.LoginRequestMessageHandler;
import com.lin.netty.chat.protocol.MessageCodec;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.*;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.LengthFieldBasedFrameDecoder;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.timeout.IdleState;
import io.netty.handler.timeout.IdleStateEvent;
import io.netty.handler.timeout.IdleStateHandler;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteOrder;

/**
 * 聊天室服务器(自定义聊天室通信所用的协议)
 * 1、接收客户端连接
 * 2、接受客户端的各种消息
 * 3、处理来自客户端的各种消息
 */
public class ChatServer {
    private static final Logger log = LoggerFactory.getLogger(ChatServer.class);

    public static void main(String[] args) {
        // 不会记录状态等数据，可以多个channel共用一个，没必要每个channel都创建一个
        final LoggingHandler LOGGING_HANDLER = new LoggingHandler();

        ServerBootstrap serverBootstrap = new ServerBootstrap();
        NioEventLoopGroup boss = new NioEventLoopGroup(1);
        NioEventLoopGroup workers = new NioEventLoopGroup();
        serverBootstrap
                .group(boss, workers)
                .childOption(ChannelOption.SO_KEEPALIVE,true)
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {

                        ChannelPipeline pipeline = ch.pipeline();
                        // 解决粘包和半包问题，保证传到后面的handler是一个完整的消息
                        pipeline.addLast(new LengthFieldBasedFrameDecoder(ByteOrder.LITTLE_ENDIAN, Integer.MAX_VALUE, 11, 4, 1, 0, true));
                        pipeline.addLast("logging", LOGGING_HANDLER);
                        pipeline.addLast(new MessageCodec());

                        // 如果5s 没收到数据，会触发IdleState.READER_IDLE事件(user event)
                        pipeline.addLast(new IdleStateHandler(60, 0, 0)); // 空闲监测
                        pipeline.addLast(new ChannelDuplexHandler() {
                            // 当用户事件触发时会被调用
                            @Override
                            public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
                                if (((IdleStateEvent) evt).state() == IdleState.READER_IDLE) {
                                    log.debug("5s 没收到数据");
                                    ctx.channel().close();
                                }
                            }
                        });

                        // 后续添加各种类型的消息handler，经过MessageCodec解码后，将消息传给对应类型的handler
                        pipeline.addLast(new LoginRequestMessageHandler());
                    }
                })
                .bind(1122);
    }
}
